package com.cictec.middleware.tde.rm.disp.receiver.handler;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.feign.distribute.MiddlewareBusWarnService;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x21TerminalMessage;

/**
 * 0x21 运行告警 中心反馈：接收指令应答确认
 * 
 * @author Administrator
 *
 */
@Component
@HandleMessages(0x21)
public class TerminalWarnHandler extends AbstractReceiverHandler {

	private static Logger logger = LoggerFactory.getLogger(TerminalWarnHandler.class);

	@Autowired
	private MiddlewareBusWarnService middlewareBusWarnService;

	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {

		// 0x80 指令应答 收到需要应答的数据包
		sendMessageToTerminal(createResponse(message, 1), session);

		Rm0x21TerminalMessage msg = (Rm0x21TerminalMessage) message;
		logger.debug("【0x21  运行告警（报警上传）】终端 {} Session {} 报警类型 {} ", message.getTerminalId(), message.getSessionId(),
				Integer.toHexString(msg.getWarnType()));

		if (msg.getWarnType() == 0x01) {
			// 处理超速报警.
			logger.debug("【0x21  运行告警（报警上传）】{} 超速报警", msg.getTerminalId());

			// 超速报警
			if (msg.getStart() == 1) {
				middlewareBusWarnService.uploadOverSpeedWarn(message.getTerminalId(), true, msg.getLat(), msg.getLng(), msg.getSpeed(), msg.getCreateTime(), null);
			} else {
				middlewareBusWarnService.uploadOverSpeedWarn(message.getTerminalId(), false, msg.getLat(), msg.getLng(), msg.getSpeed(), msg.getCreateTime(), msg.getWarnDuration());
			}
		} else {
			logger.debug("【0x21  运行告警（报警上传）】报警类型为 {} 的报警信息，不做处理", msg.getTerminalId(), msg.getWarnType());
			return;
		}

	}

}
